package net.caixiaomi.info.ui.withdraw;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.Editable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;

import net.caixiaomi.info.R;
import net.caixiaomi.info.app.CommonApp;
import net.caixiaomi.info.base.BaseActivity;
import net.caixiaomi.info.base.progressbar.CircularProgressBar;
import net.caixiaomi.info.helper.AppHelper;
import net.caixiaomi.info.model.BaseCallModel;
import net.caixiaomi.info.model.QueryWithDrawShowModel;
import net.caixiaomi.info.model.UserInfoModel;
import net.caixiaomi.info.net.RequestService;
import net.caixiaomi.info.net.ResponseCallback;
import net.caixiaomi.info.net.ResponseError;
import net.caixiaomi.info.net.RetrofitManage;
import net.caixiaomi.info.util.ToastUtil;
import net.caixiaomi.info.widgets.DefLoading;

import java.math.BigDecimal;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

/**
 * 提现
 */
public class WithdrawActivity extends BaseActivity implements TextWatcher {
    //可提现金额
    @BindView(R.id.cash)
    TextView mCash;

    @BindView(R.id.card)
    TextView mCard;
    @BindView(R.id.price)
    EditText mPrice;

    @BindView(R.id.progress)
    CircularProgressBar mProgress;

    @BindView(R.id.container)
    View mContainer;

    private QueryWithDrawShowModel mModel;

    /**
     * 管理银行卡
     */
    @OnClick(R.id.btn_manager)
    void toCardManager() {
        Intent intent = new Intent(this, ManagerCardActivity.class);
        startActivity(intent);
    }

    /**
     * 全部提现
     */
    @OnClick(R.id.btn_all_withdraw)
    void toAllWithdraw() {
        if (mModel == null)
            return;

//        if (new BigDecimal(text).compareTo(new BigDecimal(mModel.getUserMoney())) == 1) {
//            ToastUtil.s(R.string.C_WITHDRAW_FAIL_INFO_1);
//            return;
//        }
        mPrice.setText(mModel.getUserMoney());
        mPrice.setSelection(mModel.getUserMoney().length());
    }

    /**
     * 提交
     */
    @OnClick(R.id.btn_done)
    void toSave() {
        AppHelper.hideKeyboard(getCurrentFocus());
        if (mModel == null)
            return;

        if (TextUtils.isEmpty(mModel.getDefaultBankLabel())) {
            ToastUtil.s(R.string.C_INPUT_WITHDRAW_ADD_CARD);
            return;
        }

        String price = mPrice.getText().toString().trim();


        if (TextUtils.isEmpty(price) || new BigDecimal(price).compareTo(new BigDecimal("0")) == 0) {
            ToastUtil.s(R.string.C_WITHDRAW_FAIL_INFO_2);
            return;
        }

        double doublePrice = Double.valueOf(price);
        if (doublePrice < 3) {
            ToastUtil.s(R.string.C_INPUT_MONEY_LOW_3);
            return;
        }


        if (new BigDecimal(price).compareTo(new BigDecimal(mModel.getUserMoney())) == 1) {
            ToastUtil.s(R.string.C_WITHDRAW_FAIL_INFO_1);
            return;
        }
        AppHelper.sendStatistics("txtijiao", new String[]{getString(R.string.C_TERMINAL)}, new String[]{Build.BOARD});
        mLoading.show();
        JSONObject params = new JSONObject();
        params.put("totalAmount", price);
        params.put("userBankId", mModel.getUserBankId());
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel> withdraw = requestService.cashWithdraw(params);
        withdraw.enqueue(new ResponseCallback<BaseCallModel>(this) {
            @Override
            public void onSuccess(BaseCallModel model) {
                mLoading.dismiss();
                mPrice.setText("");
//                refreshData();
                ToastUtil.s(model.msg);
                onBackPressed();
            }

            @Override
            public void onFail(ResponseError error) {
                mLoading.dismiss();
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                    if (error.getCode() == 304056) {
                        onBackPressed();
                    }
                }

            }

            @Override
            public void onError() {
                mLoading.dismiss();
            }
        });

    }

    @Override
    protected int layout() {
        return R.layout.act_withdraw;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mLoading = new DefLoading(this);
        mPrice.addTextChangedListener(this);
        mPrice.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                AppHelper.sendStatistics("txshurujine");
                return false;
            }

        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        loadData();
    }

    private void loadData() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<QueryWithDrawShowModel>> userBankList = requestService.queryWithDrawShow(params);
        userBankList.enqueue(new ResponseCallback<BaseCallModel<QueryWithDrawShowModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<QueryWithDrawShowModel> model) {
                mProgress.setVisibility(View.GONE);
                mContainer.setVisibility(View.VISIBLE);
                if (model.data != null) {
                    mModel = model.data;
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(getString(R.string.C_WITHDRAW_CASH)).append(" : ").append(mModel.getUserMoney()).append(getString(R.string.C_MONEY));
                    mCash.setText(stringBuilder);

                    stringBuilder.setLength(0);
                    stringBuilder.append(getString(R.string.C_WITHDRAW_CARD)).append(": ");
                    String text = stringBuilder.toString();
                    stringBuilder.append(!TextUtils.isEmpty(mModel.getDefaultBankLabel()) ? mModel.getDefaultBankLabel() : getString(R.string.C_INPUT_WITHDRAW_ADD_CARD));

                    SpannableString spannableString = new SpannableString(stringBuilder);
                    spannableString.setSpan(new ForegroundColorSpan(ContextCompat.getColor(CommonApp.getInstance(), R.color.secondary_text)), 0, text.length(), SpannableString.SPAN_INCLUSIVE_EXCLUSIVE);
                    mCard.setText(spannableString);
                }
            }

            @Override
            public void onFail(ResponseError error) {
                mProgress.setVisibility(View.GONE);
                if (error.getCode() >= 300000 && error.getCode() <= 310000) {
                    ToastUtil.s(error.getMessage());
                }

            }

            @Override
            public void onError() {
                mProgress.setVisibility(View.GONE);
            }
        });

    }


    private void refreshData() {
        JSONObject params = new JSONObject();
        params.put("time", String.valueOf(System.currentTimeMillis()));
        RequestService requestService = RetrofitManage.getInstance().getRequestService();
        Call<BaseCallModel<UserInfoModel>> userInfoExceptPass = requestService.userInfoExceptPass(params);
        userInfoExceptPass.enqueue(new ResponseCallback<BaseCallModel<UserInfoModel>>(this) {
            @Override
            public void onSuccess(BaseCallModel<UserInfoModel> data) {
                //更新userInfo数据
                UserInfoModel userInfo = CommonApp.getUserInfo();
                UserInfoModel newUserInfo = data.data;
                newUserInfo.setToken(userInfo.getToken());
                CommonApp.setUserInfo(newUserInfo);
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(getString(R.string.C_WITHDRAW_CASH)).append(" : ").append(newUserInfo.getUserMoney()).append(getString(R.string.C_MONEY));
                if (mModel != null) mModel.setUserMoney(newUserInfo.getUserMoney());
                mCash.setText(stringBuilder);
            }

            @Override
            public void onFail(ResponseError error) {

            }

            @Override
            public void onError() {
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        //删除“.”后面超过2位后的数据
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                mPrice.setText(s);
                mPrice.setSelection(s.length()); //光标移到最后
            }
        }
        //如果"."在起始位置,则起始位置自动补0
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            mPrice.setText(s);
            mPrice.setSelection(2);
        }

    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
